package cn.stylefeng.guns.modular.service;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.modular.entity.Schedule;
import cn.stylefeng.guns.modular.mapper.ScheduleMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Map;


/**
 * @author third_e
 * @create 2019/12/18 0018-上午 8:54
 */
@Service
public class ScheduleIndexService extends ServiceImpl<ScheduleMapper,Schedule> {

    /**
     * 创建日程
     * @param schedule
     */
    @Transactional(rollbackFor = Exception.class)
    public void addSchedule(Schedule schedule){
        //保存
        //添加周数、天数
//        schedule.setWeekNum(caculateTotalWeek(schedule.getStartData(),schedule.getEndData()));
        schedule.setWeekNum( getStockWeeks(schedule.getStartData(),schedule.getEndData()));
        schedule.setDayNum(caculateTotalDay(schedule.getStartData(),schedule.getEndData()));

        schedule.setScheduleId(null);
        this.save(schedule);

    }

    /**
     * 获取一个日程详情信息
     * @param scheduleId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Schedule getOnescheduleInfo(Long scheduleId){
        return this.getById(scheduleId);
    }

    /**
     * 编辑日程
     *
     * @param schedule
     */
    @Transactional(rollbackFor = Exception.class)
    public void editSchedule(Schedule schedule){
        //添加周数、天数
//        schedule.setWeekNum(caculateTotalWeek(schedule.getStartData(),schedule.getEndData()));
        schedule.setWeekNum( getStockWeeks(schedule.getStartData(),schedule.getEndData()));
        schedule.setDayNum(caculateTotalDay(schedule.getStartData(),schedule.getEndData()));
        this.updateById(schedule);

    }

    /**
     * 删除日程
     *
     * @param scheduleId
     */
    public void deleteScheduleByID(Long scheduleId){
        this.baseMapper.deleteScheduleByID(scheduleId);
    }


    /**
     * 获取全部日程
     * @param publicOrprivate：全部状态
     * @param shareOrnotshare：筛选条件
     * @param sortBydefault：默认排序
     * @param nameOrcontent：名称/描述
     * @param beginTime：日程开始时间
     * @param endTime：日程结束时间
     * @param userId：当前用户id
     * @return
     */
    public Page<Map<String,Object>> selectSchedule(String publicOrprivate, String shareOrnotshare, String sortBydefault, String nameOrcontent, String beginTime, String endTime, Long userId){
        Page page = LayuiPageFactory.defaultPage();
        return this.baseMapper.selectSchedule(page,publicOrprivate, shareOrnotshare, sortBydefault, nameOrcontent, beginTime, endTime, userId);
    }

    /**
     * 获取一个日程及其全部日程项
     * @param scheduleId
     * @return
     */
    public Schedule selectScheduleAnditemByscheduleId(Long scheduleId, Long userId){
        return this.baseMapper.selectScheduleAnditemByscheduleId(scheduleId, userId);
    }


    /**
     * 获取今日行程
     * @return
     */
    public Collection<Schedule> getTodayScheduleService(Long userId){
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd ");
        Date date = new Date(System.currentTimeMillis());

        return this.baseMapper.getTodayScheduleMapper(userId, formatter.format(date));
    }


    /**
     * 通过框架名查找日程
     */
    public Collection<Schedule> getScheduleByframeId(Long frameId){
        return this.baseMapper.getScheduleByframeId(frameId);
    }


    /**
     * 计算天数
     * @param startTime ： 开始时间
     * @param endTime  ： 结束时间
     * @return
     */
    public static int caculateTotalDay(String startTime,String endTime) {
        SimpleDateFormat formatter =   new SimpleDateFormat( "yyyy-MM-dd");
        Long l = 0L;
        try {
            long ts = formatter.parse(startTime).getTime();
            long ts1 = formatter.parse(endTime).getTime();

            l = (ts1 - ts) / (1000 * 60 * 60 * 24)+1;
            if (l==0){
                l=1L;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return l.intValue();
    }



    /**
     *
     * 计算周数
     * @param startTime
     * @param endTime
     * @return
     */
    public static int caculateTotalWeek(String startTime,String endTime) {
        SimpleDateFormat formatter =   new SimpleDateFormat( "yyyy-MM-dd");
        Date start =null;
        Date end =null;
        Long l = 0L;
        Calendar cal=Calendar.getInstance();
        try {
            start = formatter.parse(startTime);
            end = formatter.parse(endTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        cal.setTime(start);
        long time1=cal.getTimeInMillis();
        cal.setTime(end);
        long time2=cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);
        Double days=Double.parseDouble(String.valueOf(between_days));
        if((days/7)>0 && (days/7)<=1){
            //不满一周的按一周算
            return 1;
        }else if(days/7>1){
            int day=days.intValue();
            if(day%7>0){
                return day/7+1;
            }else{
                return day/7;
            }
        }else if((days/7)==0){
            return 0;
        }
        return 0;
    }


    /**
     * 返回2个日期间有多少周
     * @param startDate  开始日期
     * @param endDate    结束日期
     * @return
     */
    public static  int getStockWeeks(String  startDate,String endDate){
        int a = 0;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar before = Calendar.getInstance();
            Calendar after = Calendar.getInstance();
            Calendar temp = Calendar.getInstance();

            before.setTime(sdf.parse(startDate));
            after.setTime(sdf.parse(endDate));

            long time1 = before.getTime().getTime();
            long time2 = after.getTime().getTime();

            if(time1>time2){//开始和结束时间对换了(有可能前后时间给错了)
                temp=before;
                before=after;
                after=temp;
            }

            int week = before.get(Calendar.DAY_OF_WEEK);
//            System.out.println("\n\n\n\n\n1、==============="+week+"===="+(before.getTimeInMillis())/(1000*3600*24));
            before.add(Calendar.DATE, -week+1);//并非周一为第一天  周日为第一天
//            System.out.println("1、==============="+week+"===="+(before.getTimeInMillis())/(1000*3600*24));
            week = after.get(Calendar.DAY_OF_WEEK);
//            System.out.println("2、==============="+week+"===="+(after.getTimeInMillis())/(1000*3600*24));
            if(week>0&&week<7){
                after.add(Calendar.DATE,  8- week);
            }
            if(week==7){
                after.add(Calendar.DATE, 1);
            }
//            System.out.println("2、==============="+week+"===="+(after.getTimeInMillis())/(1000*3600*24));
//            System.out.println("3、===="+(after.getTimeInMillis() - before.getTimeInMillis())/ (1000*3600*24*7));
            a= (int) ((after.getTimeInMillis() - before.getTimeInMillis()) / (1000*3600*24*7));
            if (a==0){
                a=1;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
//        System.out.println(a+"===============\n\n\n\n\n");
        return a;
    }


}
